package com.sabastian.gateway.authorization.auth;

import com.sabastian.gateway.authorization.GatewayAuthorizationToken;
import com.sabastian.gateway.authorization.IAuth;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

/**
 * @author Ciel Phantomhive
 * @description 认证服务实现
 * @date 2022/10/16 15:50
 */
public class AuthService implements IAuth {

    private Subject subject;

    public AuthService() {
        // 获取SecurityManager 工厂，此处使用 shiro.ini 配置文件初始化 SecurityManager
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");

        // 得到SecurityManager实例，并绑定给SecurityUtils
        SecurityUtils.setSecurityManager(factory.getInstance());

        // 得到Subject及token
        this.subject = SecurityUtils.getSubject();
    }

    @Override
    public boolean validate(String id, String token) {
        try {
            subject.login(new GatewayAuthorizationToken(id, token));
            return subject.isAuthenticated();
        } finally {
            subject.logout();
        }
    }
}
